package com.example.xjtuse_pc.mobilesafe;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xjtuse_pc.domain.TaskInfo;
import com.example.xjtuse_pc.engine.TaskInfoProvider;
import com.example.xjtuse_pc.mobilesafe.TaskManage.TaskSettingActivity;
import com.example.xjtuse_pc.utils.SystemInfoUtils;

import java.text.Format;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

public class TaskManageActivity extends Activity {

    private TextView tv_process_count, tv_mom_info,tv_task_status;
    private ListView lv_task_manager;
    private LinearLayout ll_loading;
    private TaskManageAdapter adapter;
    private List<TaskInfo> allTaskinfos, userTaskinfos, systemTaskinfos;
    private int ProcessCount;
    private long availMem;
    private  SystemInfoUtils siu;
    private SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_manage);
        tv_process_count = (TextView) findViewById(R.id.tv_process_count);
        tv_mom_info = (TextView) findViewById(R.id.tv_mom_info);
        tv_task_status = (TextView) findViewById(R.id.tv_task_status);
        sp=getSharedPreferences("config", MODE_PRIVATE);
        setTitle();
        ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        lv_task_manager = (ListView) findViewById(R.id.lv_task_manager);

        fillDate();
        /**
         * listview滚动监听
         */
        lv_task_manager.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(userTaskinfos!=null&&systemTaskinfos!=null){
                    if(firstVisibleItem>userTaskinfos.size()){
                        tv_task_status.setText("系统进程：" + systemTaskinfos.size() + "个");
                    }else {
                        tv_task_status.setText("用户进程：" + userTaskinfos.size() + "个");
                    }
                }
            }
        });

        lv_task_manager.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TaskInfo ti;
                if (position == 0) {
                    return ;
                } else if (position == (userTaskinfos.size() + 1)) {
                    return ;
                } else if (position <= userTaskinfos.size()) {
                    int newpostion = position - 1;
                    ti = userTaskinfos.get(newpostion);
                } else {
                    int newpostion = position - 2 - userTaskinfos.size();
                    ti = systemTaskinfos.get(newpostion);
                }
                if(ti.getPackname().equals(getPackageName())){
                    return;

                }
                ViewHolder vh= (ViewHolder) view.getTag();
                if(ti.isCheck()){
                    ti.setCheck(false);
                    vh.cb.setChecked(false);

                }else {
                    ti.setCheck(true);
                    vh.cb.setChecked(true);
                }
            }
        });
    }

    private void setTitle() {
       siu = new SystemInfoUtils(this);
        ProcessCount=siu.getRunningProcessCount();
        availMem=siu.getAvilMem();
        tv_process_count.setText("运行中进程:" + ProcessCount + "个");
        tv_mom_info.setText("剩余/总内存:" + android.text.format.Formatter.formatFileSize(this,availMem)+ "/" + android.text.format.Formatter.formatFileSize(this, siu.getLowTotalMem()));
    }

    /**
     * 填充数据
     */
    private void fillDate() {
        ll_loading.setVisibility(View.VISIBLE);
        adapter = new TaskManageAdapter();
        new Thread(new Runnable() {
            @Override
            public void run() {
                allTaskinfos = TaskInfoProvider.getTaskInfos(TaskManageActivity.this);
                userTaskinfos = new ArrayList<TaskInfo>();
                systemTaskinfos = new ArrayList<TaskInfo>();

                for (TaskInfo s : allTaskinfos) {
                    if (s.isUserTask()) {
                        userTaskinfos.add(s);
                    } else {
                        systemTaskinfos.add(s);
                    }
                }


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ll_loading.setVisibility(View.INVISIBLE);
                        lv_task_manager.setAdapter(adapter);
                    }
                });

            }

        }).start();
    }

    public void selectAll(View view) {
        for(TaskInfo i:allTaskinfos){
            if(i.getPackname().equals(getPackageName())){
                continue;
            }
            i.setCheck(true);
        }
        adapter.notifyDataSetChanged();
    }

    public void selectOpp(View view) {
        for(TaskInfo i:allTaskinfos){
            if(i.getPackname().equals(getPackageName())){
                continue;
            }
            i.setCheck(!i.isCheck());
        }
        adapter.notifyDataSetChanged();

    }

    public void killAll(View view) {
        int count=0;
        long mem=0;
        ActivityManager am= (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
       List<TaskInfo> ls =new ArrayList<TaskInfo>();
        for(TaskInfo i:allTaskinfos){
            if(i.isCheck()){
                am.killBackgroundProcesses(i.getPackname());
                if(i.isUserTask()){
                    userTaskinfos.remove(i);
                }else {
                    systemTaskinfos.remove(i);
                }
                count++;
                mem+=i.getMemSize();
                ls.add(i);
            }

        }
        allTaskinfos.removeAll(ls);
        adapter.notifyDataSetChanged();
        Toast.makeText(TaskManageActivity.this,"系统杀死了 "+count+"个进程"+"，释放了"+ android.text.format.Formatter.formatFileSize(this,mem)+"内存",Toast.LENGTH_SHORT ).show();
        ProcessCount-=count;
        availMem+=mem;
        tv_process_count.setText("运行中进程:" + ProcessCount + "个");
        tv_mom_info.setText("剩余/总内存:" + android.text.format.Formatter.formatFileSize(this,availMem)+ "/" + android.text.format.Formatter.formatFileSize(this, siu.getLowTotalMem()));

    }

    public void setALL(View view) {
        Intent intent=new Intent(TaskManageActivity.this, TaskSettingActivity.class);
        startActivityForResult(intent, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        adapter.notifyDataSetChanged();
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 进程管理适配器
     */
    public class TaskManageAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if(sp.getBoolean("System_status",false)){
                return systemTaskinfos.size() + userTaskinfos.size() + 2;
            }
            return  userTaskinfos.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TaskInfo ti;
            if (position == 0) {
                TextView tv = new TextView(TaskManageActivity.this);
                tv.setTextColor(Color.WHITE);
                tv.setBackgroundColor(Color.GRAY);
                tv.setText("用户进程：" + userTaskinfos.size() + "个");
                return tv;
            } else if (position == (userTaskinfos.size() + 1)) {
                TextView tv = new TextView(TaskManageActivity.this);
                tv.setTextColor(Color.WHITE);
                tv.setBackgroundColor(Color.GRAY);
                tv.setText("系统进程：" + systemTaskinfos.size() + "个");
                return tv;
            } else if (position <= userTaskinfos.size()) {
                int newpostion = position - 1;
                ti = userTaskinfos.get(newpostion);
            } else {
                int newpostion = position - 2 - userTaskinfos.size();
                ti = systemTaskinfos.get(newpostion);
            }

            View view;
            ViewHolder vh;
            if (convertView != null && convertView instanceof RelativeLayout) {
                view = convertView;
                vh = (ViewHolder) view.getTag();
            } else {
                view = View.inflate(TaskManageActivity.this, R.layout.list_item_task, null);
                vh = new ViewHolder();
                vh.icon = (ImageView) view.findViewById(R.id.iv_task_icon);
                vh.name = (TextView) view.findViewById(R.id.tv_task_name);
                vh.memsize = (TextView) view.findViewById(R.id.tv_task_memsize);
                vh.cb= (CheckBox) view.findViewById(R.id.cb_task_status);
                view.setTag(vh);
            }
            vh.icon.setImageDrawable(ti.getIcon());
            vh.name.setText(ti.getName());
            vh.memsize.setText("内存占用：" + android.text.format.Formatter.formatFileSize(TaskManageActivity.this, ti.getMemSize()));
            vh.cb.setChecked(ti.isCheck());
            if(getPackageName().equals(ti.getPackname())){
                vh.cb.setVisibility(View.INVISIBLE);
            }else {
                vh.cb.setVisibility(View.VISIBLE);
            }
            return view;
        }
    }

    class ViewHolder {
        ImageView icon;
        TextView name;
        TextView memsize;
        CheckBox cb;
    }
}
